// pages/place-order/place-order.js
import { calculateOrder, getConfigPrice, getGoodsList, getTopGood, updateUserPhone } from "../../api/api";

Page({
    data: {
        categories: [],
        showProductDetail: false,
        showCar: false,
        activeCategory: 0,
        products: [],
        cart: [],
        selectedProduct: [],
        total: 0,
        count: 0,
        type: 1,
        product: {},
        phone: '',
        title: '',
        topGood:{},
		configPrice: []
    },

    onLoad(options) {
      this.setData({
        type: options.type
      })
    },

    onShow() {
        getGoodsList({type: this.data.type})
            .then(res => {
                let categories = []
                Object.keys(res.data).forEach(key => {
                    categories.push({
                        name: key,
                        products: res.data[key]
                    })
                })

                this.setData({
                    categories,
                    products: categories[0].products,
                    phone: getApp().globalData.phone
                })
            })

        getTopGood()
        .then(res => {
            console.log(res)
            const item = res.data.good
            item.specifications = JSON.parse(item.specifications)
            const json = []
            Object.keys(item.specifications).forEach(key => {
                if (item.specifications[key].length > 0) {
                    json.push({
                        name: key,
                        value: item.specifications[key],
                        selected: item.specifications[key][0]
                    })
                }
            })
            item.specifications = json
            item.count = 1
            this.setData({
                topGood: item,
                title: res.data.title
            })
        })

		getConfigPrice()
		.then(res => {
			this.setData({
				configPrice: res.data
			})
		})
    },



  // 获取用户手机号
  getPhoneNumber(e) {
    updateUserPhone({code: e.detail.code})
        .then(res => {
          getApp().globalData.phone = res.data.phone
          this.setData({
            phone: res.data.phone
          })
        })
  },


    /** 计算订单  */
    async handleCalculate(selectedProduct) {
        // 处理支付逻辑
        const commodityList = []
        selectedProduct.forEach(item => {
            const specifications = {}
            item.specifications.forEach(specification => {
                specifications[specification.name] = specification.selected
            })
            const obj = {
                id: item.id,
                name: item.name,
                amount: item.count,
                specifications: JSON.stringify(specifications)
            }

            commodityList.push(obj)
        })
        return calculateOrder({
            voucherId: this.data.voucherId,
            commodityList
        })
        .then(res => {
            return {total: res.data.orderPrice}
        })
    },

    handleShowCar() {
        if(!this.data.selectedProduct.length){
            return
        }
        this.setData({
            showCar: !this.data.showCar
        })
    },

    handleCategoryChange(e) {
        const {value} = e.detail;
        this.setData({
            activeCategory: value,
            products: this.data.categories[value].products,
        });
    },

    selectProduct(e) {
        // 处理商品选择逻辑
        const item = e.currentTarget.dataset.data
        item.specifications = JSON.parse(item.specifications)
        const json = []
        Object.keys(item.specifications).forEach(key => {
            if (item.specifications[key].length > 0) {
                json.push({
                    name: key,
                    value: item.specifications[key],
                    selected: item.specifications[key][0]
                })
            }
        })
        item.specifications = json
        item.count = 1
        this.setData({
            product: item,
            showProductDetail: true
        })
    },

    handleSelected(e) {
        let item = e.detail
        const selectedProduct = this.data.selectedProduct
        const specifications_s = {}
        var specifications_v = ''
        item.specifications.forEach((v,i,array) => {
          specifications_s[v.name] = v.selected
          specifications_v += v.selected + (i < array.length - 1?',':'')
        })
        item.specifications_s = specifications_s
        item.specifications_v = specifications_v
        selectedProduct.push(item)
        let count = selectedProduct.reduce((count, item) => {
            return count + item.count
        }, 0)
        this.setData({
            selectedProduct,
            showProductDetail: false,
            count
        })

        setTimeout(async () => {
            let { total } = await this.handleCalculate(selectedProduct)
            console.log( total)
            this.setData({
                total
            })
        })
    },

    goToCheckout() {
        if (this.data.selectedProduct.length === 0) {
            wx.showToast({
                title: '请选择商品',
                icon: 'none'
            })
            return
        }
        // 处理去结算逻辑
        console.log('Go to checkout',this.data.selectedProduct);
        getApp().globalData.selectedProduct = this.data.selectedProduct;
        getApp().globalData.count = this.data.count || 1;
        getApp().globalData.total = this.data.total;
        wx.navigateTo({
            url: '/pages/order-summary/order-summary'
        })
    },

    topGoodToPay(){
        const selectedProduct =  this.data.topGood
        const specifications_s = {}
        selectedProduct.specifications.forEach(v => {
            specifications_s[v.name] = v.selected
        })
        selectedProduct.specifications_s = specifications_s
        selectedProduct.count = 1

        console.log(selectedProduct)
        this.setData({
            selectedProduct: [selectedProduct],
        })

        setTimeout(() => {
            this.goToCheckout()
        })
    },

    async removeProduct(e) {
        const id = e.currentTarget.dataset.id
        let selectedProduct = this.data.selectedProduct
        let item = selectedProduct.filter(product => product.id === id)[0]
        if (item.count > 1) {
            item.count--
        } else {
            selectedProduct = selectedProduct.filter(item => item.id !== id)
        }

        let { total } = await this.handleCalculate(selectedProduct)
        let count = selectedProduct.reduce((count, item) => {
            return count + item.count
        }, 0)
        this.setData({
            selectedProduct: selectedProduct,
            total,
            count
        })
    },

    async addProduct(e) {
        const id = e.currentTarget.dataset.id
        let selectedProduct = this.data.selectedProduct
        let item = selectedProduct.filter(product => product.id === id)[0]
        item.count++
        selectedProduct = selectedProduct.filter(item => item.id !== id)
        selectedProduct.push(item)

        let { total } = await this.handleCalculate(selectedProduct)
        let count = selectedProduct.reduce((count, item) => {
            return count + item.count
        }, 0)
        this.setData({
            selectedProduct: selectedProduct,
            total: total,
            count
        })
    },

    onVisibleChange() {
        this.setData({
            showProductDetail: false,
            showCar: false,
            product: {}
        })
    }
});
